package com.windoent.yugioh.ui.activity.saishi;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.object.DeleteObjectRequest;
import com.tencent.cos.xml.model.object.DeleteObjectResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.windoent.yugioh.MainActivity;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.multi.SettingImageUpLoadAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.SubmitPhotoDataBean;
import com.windoent.yugioh.bean.multi.FeedbackUpLoadImageBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.GlideLoadEngine;
import com.windoent.yugioh.help.txoss.CosServiceFactory;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.JumpHelper;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.utils.some.utilcode.util.ImageUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.functions.Consumer;
import okhttp3.Call;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * author : robert
 * date   : 2021/5/24 10:53
 * desc   :店级积分赛提交资料
 */
public class StoreGradeCommitDocumentActvity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private LinearLayout mLlJump;
    private Button mBtnGetCode;
    private RecyclerView mRecyclerViewThreePic;
    private RecyclerView mRecyclerViewChampionPic;
    private RecyclerView mRecyclerViewYajunPic;
    private RecyclerView mRecyclerViewFourTopPic;
    private RecyclerView mRecyclerViewFourBTopPic;
    private TextView mTvXingThreePic;
    private TextView mTvXingChampionPic;


    private int type = -1;//点击的item，0冠军，1亚军，2四强,3三张,4四强b
    private SettingImageUpLoadAdapter adapterYajun;//1亚军
    private SettingImageUpLoadAdapter adapterChampion;//0冠军
    private SettingImageUpLoadAdapter adapterTopFour;//2四强
    private SettingImageUpLoadAdapter adapterThreePic;//3三张
    private SettingImageUpLoadAdapter adapterTopFourB;//4四强b
    private String id;
    private int applayStatus = -1;
    private boolean ignore;

    @Override
    public int getLayout() {
        return R.layout.activity_saishi_commit_document_store_grade;
    }

    @Override
    public void initView() {
        super.initView();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mLlJump = (LinearLayout) findViewById(R.id.ll_jump);
        mBtnGetCode = (Button) findViewById(R.id.btn_get_code);
        mRecyclerViewThreePic = (RecyclerView) findViewById(R.id.recycler_view_three_pic);
        mRecyclerViewChampionPic = (RecyclerView) findViewById(R.id.recycler_view_champion_pic);
        mRecyclerViewYajunPic = (RecyclerView) findViewById(R.id.recycler_view_yajun_pic);
        mRecyclerViewFourTopPic = (RecyclerView) findViewById(R.id.recycler_view_four_top_pic);
        mRecyclerViewFourBTopPic = (RecyclerView) findViewById(R.id.recycler_view_four_b_top_pic);

        mTvXingThreePic = (TextView) findViewById(R.id.tv_xing_three_pic);
        mTvXingChampionPic = (TextView) findViewById(R.id.tv_xing_champion_pic);
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        applayStatus = intent.getIntExtra("applayStatus", -1);
        ignore = intent.getBooleanExtra("ignore", false);
        jumpUi(ignore);
        showBtnStatus(applayStatus);

        cosXmlService = CosServiceFactory.getCosXmlService(this, bucketRegion, Constants.COS_SECRET_ID, Constants.COS_SECRET_KEY, true);
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        transferManager = new TransferManager(cosXmlService, transferConfig);
        initThreePicAdapter();
        initChampionAdapter();
        initYaJunAdapter();
        inittopFourAdapter();
        inittopFourBAdapter();
        if (applayStatus != 1)
            getAgainstPhoto();
    }

    //查看比赛过程图片
    private void getAgainstPhoto() {
        showLoadingDialog("");
        PhoneLive.getAgainstPhoto(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            SubmitPhotoDataBean json = gson.fromJson(response, SubmitPhotoDataBean.class);
                            SubmitPhotoDataBean.DataBean data = json.getData();
                            if (data != null) {
                                SubmitPhotoDataBean.DataBean.ResBean res = data.getRes();
                                if (res != null) {
                                  /*adapterYajun;//1亚军
                                    adapterChampion;//0冠军
                                    adapterTopFour;//2四强
                                    adapterThreePic;//3三张
                                    adapterTopFourB;//4四强b*/
                                    List<String> live = res.getLive();
                                    List<String> champion = res.getChampion();
                                    List<String> runnerUp = res.getRunnerUp();
                                    List<String> topFourA = res.getTopFourA();
                                    List<String> topFourB = res.getTopFourB();
                                    int status = res.getStatus();
                                    List<FeedbackUpLoadImageBean> liveData = getUpLoadImageBean(live);
                                    List<FeedbackUpLoadImageBean> championData = getUpLoadImageBean(champion);
                                    List<FeedbackUpLoadImageBean> runnerUpData = getUpLoadImageBean(runnerUp);
                                    List<FeedbackUpLoadImageBean> topFourAData = getUpLoadImageBean(topFourA);
                                    List<FeedbackUpLoadImageBean> topFourBData = getUpLoadImageBean(topFourB);
                                    adapterThreePic.setNewInstance(liveData);
                                    adapterChampion.setNewInstance(championData);
                                    adapterYajun.setNewInstance(runnerUpData);
                                    adapterTopFour.setNewInstance(topFourAData);
                                    adapterTopFourB.setNewInstance(topFourBData);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //获得上传图片（初始）
    private List<FeedbackUpLoadImageBean> getUpLoadImageBean(List<String> list) {
        List<FeedbackUpLoadImageBean> arrayList = new ArrayList<>();
        arrayList.clear();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                if (BaseMethod.notNull(s)) {
                    FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                    bean.setUrl(s);
                    bean.setItemType(0);
                    arrayList.add(bean);
                }
            }
        }
        FeedbackUpLoadImageBean feedback = new FeedbackUpLoadImageBean();
        feedback.setItemType(1);
        arrayList.add(feedback);
        return arrayList;
    }

    private void initThreePicAdapter() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerViewThreePic.setLayoutManager(gridLayoutManager);
        adapterThreePic = new SettingImageUpLoadAdapter();
        List<FeedbackUpLoadImageBean> listUpSetting = new ArrayList<>();
        listUpSetting.clear();
        FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
        bean.setItemType(1);
        listUpSetting.add(bean);
        adapterThreePic.setNewInstance(listUpSetting);
        mRecyclerViewThreePic.setAdapter(adapterThreePic);
        adapterThreePic.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<FeedbackUpLoadImageBean> data = adapterThreePic.getData();
                int size = data.size();
                if (position == size - 1) {
                    if (adapterThreePic != null) {
                        List<FeedbackUpLoadImageBean> imageBeans = adapterThreePic.getData();
                        if (imageBeans != null) {
                            if (imageBeans.size() > 3) {
                                ToastUtils.showText(getString(R.string.string_photo_limit_three));
                                return;
                            }
                        }
                    }
                    type = 3;
                    permissionSelecPic();
                } else {
                    if (data != null) {
                        FeedbackUpLoadImageBean upSettingBean = data.get(position);
                        if (upSettingBean != null) {
                            String url = upSettingBean.getUrl();
                            if (BaseMethod.notNull(url))
                                JumpHelper.startPhotoViewPager(mContext, position, data);
                        }
                    }
                }

            }
        });
        adapterThreePic.setDeleteItemClickListener(new SettingImageUpLoadAdapter.onDeletePicItemClickListener() {
            @Override
            public void onDeletePicItemClick(int position) {
                List<FeedbackUpLoadImageBean> data = adapterThreePic.getData();
                if (data != null) {
                    removeOss(data.get(position).getUrl());
                    data.remove(position);
                    adapterThreePic.setNewInstance(data);
                    adapterThreePic.notifyDataSetChanged();
                }
            }
        });
    }

    private void initChampionAdapter() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerViewChampionPic.setLayoutManager(gridLayoutManager);
        adapterChampion = new SettingImageUpLoadAdapter();
        List<FeedbackUpLoadImageBean> listUpSetting = new ArrayList<>();
        listUpSetting.clear();
        FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
        bean.setItemType(1);
        listUpSetting.add(bean);
        adapterChampion.setNewInstance(listUpSetting);
        mRecyclerViewChampionPic.setAdapter(adapterChampion);
        adapterChampion.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<FeedbackUpLoadImageBean> data = adapterChampion.getData();
                int size = data.size();
                if (position == size - 1) {
                    if (adapterChampion != null) {
                        List<FeedbackUpLoadImageBean> imageBeans = adapterChampion.getData();
                        if (imageBeans != null) {
                            if (imageBeans.size() > 3) {
                                ToastUtils.showText(getString(R.string.string_photo_limit_three));
                                return;
                            }
                        }
                    }
                    type = 0;
                    permissionSelecPic();
                } else {
                    if (data != null) {
                        FeedbackUpLoadImageBean upSettingBean = data.get(position);
                        if (upSettingBean != null) {
                            String url = upSettingBean.getUrl();
                            if (BaseMethod.notNull(url))
                                JumpHelper.startPhotoViewPager(mContext, position, data);
                        }
                    }
                }

            }
        });
        adapterChampion.setDeleteItemClickListener(new SettingImageUpLoadAdapter.onDeletePicItemClickListener() {
            @Override
            public void onDeletePicItemClick(int position) {
                List<FeedbackUpLoadImageBean> data = adapterChampion.getData();
                if (data != null) {
                    removeOss(data.get(position).getUrl());
                    data.remove(position);
                    adapterChampion.setNewInstance(data);
                    adapterChampion.notifyDataSetChanged();
                }
            }
        });
    }

    private void initYaJunAdapter() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerViewYajunPic.setLayoutManager(gridLayoutManager);
        adapterYajun = new SettingImageUpLoadAdapter();
        List<FeedbackUpLoadImageBean> listUpSetting = new ArrayList<>();
        listUpSetting.clear();
        FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
        bean.setItemType(1);
        listUpSetting.add(bean);
        adapterYajun.setNewInstance(listUpSetting);
        mRecyclerViewYajunPic.setAdapter(adapterYajun);
        adapterYajun.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<FeedbackUpLoadImageBean> data = adapterYajun.getData();
                int size = data.size();
                if (position == size - 1) {
                    if (adapterYajun != null) {
                        List<FeedbackUpLoadImageBean> imageBeans = adapterYajun.getData();
                        if (imageBeans != null) {
                            if (imageBeans.size() > 3) {
                                ToastUtils.showText(getString(R.string.string_photo_limit_three));
                                return;
                            }
                        }
                    }
                    type = 1;
                    permissionSelecPic();
                } else {
                    if (data != null) {
                        FeedbackUpLoadImageBean upSettingBean = data.get(position);
                        if (upSettingBean != null) {
                            String url = upSettingBean.getUrl();
                            if (BaseMethod.notNull(url))
                                JumpHelper.startPhotoViewPager(mContext, position, data);
                        }
                    }
                }

            }
        });
        adapterYajun.setDeleteItemClickListener(new SettingImageUpLoadAdapter.onDeletePicItemClickListener() {
            @Override
            public void onDeletePicItemClick(int position) {
                List<FeedbackUpLoadImageBean> data = adapterYajun.getData();
                if (data != null) {
                    removeOss(data.get(position).getUrl());
                    data.remove(position);
                    adapterYajun.setNewInstance(data);
                    adapterYajun.notifyDataSetChanged();
                }
            }
        });
    }

    private void inittopFourAdapter() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerViewFourTopPic.setLayoutManager(gridLayoutManager);
        adapterTopFour = new SettingImageUpLoadAdapter();
        List<FeedbackUpLoadImageBean> listUpSetting = new ArrayList<>();
        listUpSetting.clear();
        FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
        bean.setItemType(1);
        listUpSetting.add(bean);
        adapterTopFour.setNewInstance(listUpSetting);
        mRecyclerViewFourTopPic.setAdapter(adapterTopFour);
        adapterTopFour.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<FeedbackUpLoadImageBean> data = adapterTopFour.getData();
                int size = data.size();
                if (position == size - 1) {
                    if (adapterTopFour != null) {
                        List<FeedbackUpLoadImageBean> imageBeans = adapterTopFour.getData();
                        if (imageBeans != null) {
                            if (imageBeans.size() > 3) {
                                ToastUtils.showText(getString(R.string.string_photo_limit_three));
                                return;
                            }
                        }
                    }
                    type = 2;
                    permissionSelecPic();
                } else {
                    if (data != null) {
                        FeedbackUpLoadImageBean upSettingBean = data.get(position);
                        if (upSettingBean != null) {
                            String url = upSettingBean.getUrl();
                            if (BaseMethod.notNull(url))
                                JumpHelper.startPhotoViewPager(mContext, position, data);
                        }
                    }
                }

            }
        });
        adapterTopFour.setDeleteItemClickListener(new SettingImageUpLoadAdapter.onDeletePicItemClickListener() {
            @Override
            public void onDeletePicItemClick(int position) {
                List<FeedbackUpLoadImageBean> data = adapterTopFour.getData();
                if (data != null) {
                    removeOss(data.get(position).getUrl());
                    data.remove(position);
                    adapterTopFour.setNewInstance(data);
                    adapterTopFour.notifyDataSetChanged();
                }
            }
        });
    }

    private void inittopFourBAdapter() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerViewFourBTopPic.setLayoutManager(gridLayoutManager);
        adapterTopFourB = new SettingImageUpLoadAdapter();
        List<FeedbackUpLoadImageBean> listUpSetting = new ArrayList<>();
        listUpSetting.clear();
        FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
        bean.setItemType(1);
        listUpSetting.add(bean);
        adapterTopFourB.setNewInstance(listUpSetting);
        mRecyclerViewFourBTopPic.setAdapter(adapterTopFourB);
        adapterTopFourB.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<FeedbackUpLoadImageBean> data = adapterTopFourB.getData();
                int size = data.size();
                if (position == size - 1) {
                    if (adapterTopFourB != null) {
                        List<FeedbackUpLoadImageBean> imageBeans = adapterTopFourB.getData();
                        if (imageBeans != null) {
                            if (imageBeans.size() > 3) {
                                ToastUtils.showText(getString(R.string.string_photo_limit_three));
                                return;
                            }
                        }
                    }
                    type = 4;
                    permissionSelecPic();
                } else {
                    if (data != null) {
                        FeedbackUpLoadImageBean upSettingBean = data.get(position);
                        if (upSettingBean != null) {
                            String url = upSettingBean.getUrl();
                            if (BaseMethod.notNull(url))
                                JumpHelper.startPhotoViewPager(mContext, position, data);
                        }
                    }
                }

            }
        });
        adapterTopFourB.setDeleteItemClickListener(new SettingImageUpLoadAdapter.onDeletePicItemClickListener() {
            @Override
            public void onDeletePicItemClick(int position) {
                List<FeedbackUpLoadImageBean> data = adapterTopFourB.getData();
                if (data != null) {
                    removeOss(data.get(position).getUrl());
                    data.remove(position);
                    adapterTopFourB.setNewInstance(data);
                    adapterTopFourB.notifyDataSetChanged();
                }
            }
        });
    }

    //删除腾讯云对象存储
    private void removeOss(String url) {
        String cosPath = BaseMethod.getUrlImageSubString(url);
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucket,
                cosPath);
        cosXmlService.deleteObjectAsync(deleteObjectRequest,
                new CosXmlResultListener() {
                    @Override
                    public void onSuccess(CosXmlRequest cosXmlRequest, CosXmlResult result) {
                        DeleteObjectResult deleteObjectResult = (DeleteObjectResult) result;
                        LogUtils.d("delete-->:" + deleteObjectResult.httpCode);
                    }

                    @Override
                    public void onFail(CosXmlRequest cosXmlRequest,
                                       CosXmlClientException clientException,
                                       CosXmlServiceException serviceException) {
                        if (clientException != null) {
                            clientException.printStackTrace();
                        } else {
                            serviceException.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mLlJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //确认跳过
                showJumpDialog();
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*adapterYajun;//1亚军,
                adapterChampion;//0冠军
                adapterTopFour;//2四强
                adapterThreePic;//3三张
                adapterTopFourB;//4四强b*/
                //申请结束比赛状态 ：0没有操作权限 1,还没申请 (结束比赛) 2，已经申请，正在审核（审核中） 3，审核通过 （已结束比赛） 4，审核不通过（重新提交）
                if (applayStatus == 1) {
                    List<FeedbackUpLoadImageBean> runnerupData = adapterYajun.getData();
                    List<FeedbackUpLoadImageBean> championData = adapterChampion.getData();
                    List<FeedbackUpLoadImageBean> topfouraData = adapterTopFour.getData();
                    List<FeedbackUpLoadImageBean> liveData = adapterThreePic.getData();
                    List<FeedbackUpLoadImageBean> topfourbData = adapterTopFourB.getData();
                    String runnerup = getListStr(runnerupData);
                    String champion = getListStr(championData);
                    String topfoura = getListStr(topfouraData);
                    String live = getListStr(liveData);
                    String topfourb = getListStr(topfourbData);
                    submitAgainstPhoto(runnerup, champion, topfoura, live, topfourb);
                } else if (applayStatus == 2) {
                    ToastUtils.showText(getString(R.string.string_submit_photo_reviewing_warn));
                } else if (applayStatus == 3) {
                    ToastUtils.showText(getString(R.string.string_sure_saiguo_pass_warn));
                } else if (applayStatus == 4) {
                    List<FeedbackUpLoadImageBean> runnerupData = adapterYajun.getData();
                    List<FeedbackUpLoadImageBean> championData = adapterChampion.getData();
                    List<FeedbackUpLoadImageBean> topfouraData = adapterTopFour.getData();
                    List<FeedbackUpLoadImageBean> liveData = adapterThreePic.getData();
                    List<FeedbackUpLoadImageBean> topfourbData = adapterTopFourB.getData();
                    String runnerup = getListStr(runnerupData);
                    String champion = getListStr(championData);
                    String topfoura = getListStr(topfouraData);
                    String live = getListStr(liveData);
                    String topfourb = getListStr(topfourbData);
                    modifyAgainstPhoto(runnerup, champion, topfoura, live, topfourb);
                }
            }
        });
    }

    //确认跳过
    private void showJumpDialog() {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_submit_photo_jump_warning));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesStr(getString(R.string.string_continue));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                submitPhotoJump();
            }
        });
        dialog.show();
    }

    //娱乐赛跳过图片提交
    private void submitPhotoJump() {
        showLoadingDialog("");
        PhoneLive.submitPhotoJump(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_jump_game_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    startActivity(new Intent(mContext, MainActivity.class));
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_jump_game_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //提交比赛过程图片
    private void submitAgainstPhoto(String runnerup, String champion, String topfoura, String live, String topfourb) {
        showLoadingDialog("");
        PhoneLive.submitAgainstPhoto(getUserToken(), id, live, champion, runnerup, topfoura, topfourb, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_reward_sure_submit)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    applayStatus = 2;
                                    showBtnStatus(applayStatus);
                                    startActivity(new Intent(mContext, MainActivity.class));
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_submit_grade_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //修改比赛过程图片
    private void modifyAgainstPhoto(String runnerup, String champion, String topfoura, String live, String topfourb) {
        showLoadingDialog("");
        PhoneLive.modifyAgainstPhoto(getUserToken(), id, live, champion, runnerup, topfoura, topfourb, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_reward_sure_submit)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    applayStatus = 2;
                                    showBtnStatus(applayStatus);
                                    startActivity(new Intent(mContext, MainActivity.class));
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_submit_grade_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //提交图片json
    private String getListStr(List<FeedbackUpLoadImageBean> data) {
        if (data != null) {
            List<String> list = new ArrayList<>();
            list.clear();
            for (int i = 0; i < data.size(); i++) {
                FeedbackUpLoadImageBean feedback = data.get(i);
                if (feedback != null) {
                    String url = feedback.getUrl();
                    if (BaseMethod.notNull(url)) {
                        String subString = BaseMethod.getUrlImageSubString(url);
                        list.add(subString);
                    }
                }
            }
            if (list.size() > 0)
                return gson.toJson(list);
            else return "";
        }
        return "";
    }


    //点击了从相册选择
    private void permissionSelecPic() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_CALENDAR)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                    /*        adapterYajun;//1亚军
                            adapterChampion;//0冠军
                            adapterTopFour;//2四强
                            adapterThreePic;//3三张
                            adapterTopFourB;//4四强b*/
                            if (type == 0) {
                                startImagePick(adapterChampion);
                            } else if (type == 1) {
                                startImagePick(adapterYajun);
                            } else if (type == 2) {
                                startImagePick(adapterTopFour);
                            } else if (type == 3) {
                                startImagePick(adapterThreePic);
                            } else if (type == 4) {
                                startImagePick(adapterTopFourB);
                            }
                        } else {
                            ToastUtils.showText(getString(R.string.string_no_permission));
                        }
                    }
                });
    }

    private void startImagePick(SettingImageUpLoadAdapter adapter) {
        //图片
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .capture(true)  // 使用相机，和 captureStrategy 一起使用
                .captureStrategy(new CaptureStrategy(true, getPackageName() + ".provider"))
//        R.style.Matisse_Zhihu (light mode)
//        R.style.Matisse_Dracula (dark mode)
//                .theme(R.style.Matisse_Dracula)
                .countable(true)
                .maxSelectable(adapter != null && adapter.getData().size() > 0 ? 4 - adapter.getData().size() : 3)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                            add(MimeType.JPEG);
                        }};
                    }

                    @Override
                    public IncapableCause filter(Context context, Item item) {
                        try {
                            InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(inputStream, null, options);
                            int width = options.outWidth;
                            int height = options.outHeight;

//                            if (width >= 500)
//                                return new IncapableCause("宽度超过500px");

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }


                        return null;
                    }
                })
//                .gridExpectedSize((int) getResources().getDimension(R.dimen.imageSelectDimen))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.87f)
                .imageEngine(new GlideLoadEngine())
                .forResult(Constants.REQUEST_CODE_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                List<Uri> pathList = Matisse.obtainResult(data);
                if (pathList != null && pathList.size() > 0) {
                    for (int i = 0; i < pathList.size(); i++) {
                        String pathImage = ImageUtils.getRealFilePath(this, pathList.get(i));
                        LogUtils.d("Single image path ---- " + pathList.get(0) + ",pathImage:" + pathImage);
                        //do something with the image (save it to some directory or whatever you need to do with it here)
                        if (BaseMethod.notNull(pathImage) && pathImage.contains(".") && pathImage.contains("/")) {
                            int index = pathImage.lastIndexOf(".");
                            int indexName = pathImage.lastIndexOf("/");
                            String type = pathImage.substring(index + 1, pathImage.length());
                            String fileNmae = pathImage.substring(indexName + 1, pathImage.length());
                            LogUtils.d("type ---- " + type + ",indexName:" + indexName);
                            LogUtils.d("pathpath2:" + pathImage + ",filename:" + fileNmae);
                            lubanCompress(fileNmae, pathImage, type);//鲁班压缩
                        }
                    }
                }
            }
        }
    }

    private CosXmlService cosXmlService;
    private TransferManager transferManager;
    private String bucketRegion = "ap-shanghai";// 存储桶所在地域简称，例如广州地区是 ap-guangzhou
    private COSXMLUploadTask cosxmlTask;
    private String bucket = "yugioh-1258002530"; //存储桶，格式：BucketName-APPID

    //鲁班压缩
    private void lubanCompress(String fileNmae, String pathImage, String type) {
        Luban.with(this)
                .load(pathImage)
                .ignoreBy(100)
                .setTargetDir(Objects.requireNonNull(getExternalCacheDir()).getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        String filePath = file.getPath();
                        ExecutorService executor = Executors.newSingleThreadExecutor();
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                uploadTxOss(filePath);
                            }
                        });
                        //上传图片
                        LogUtils.d("imagesize压缩前:" + BaseMethod.getBitmapsize(ImageUtils.getBitmap(pathImage)) / 1024 + "KB," + ",压缩后：" + BaseMethod.getBitmapsize(ImageUtils.getBitmap(filePath)) / 1024 + "KB,");
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        LogUtils.d("pathpath5:" + e.getMessage());
                        ToastUtils.showText(e.getMessage());
                    }
                }).launch();
    }

    private void uploadTxOss(String currentUploadPath) {
        LogUtils.d("txoss-->0:" + currentUploadPath);
        if (TextUtils.isEmpty(currentUploadPath)) {
            ToastUtils.showText(getString(R.string.string_please_select_file));
            return;
        }
        File file = new File(currentUploadPath);
        final String cosPath = "Android" + File.separator + System.currentTimeMillis() + file.getName();
        String uploadId = null;
        // 上传文件
        cosxmlTask = transferManager.upload(bucket, cosPath,
                currentUploadPath, uploadId);
        //设置上传进度回调
        cosxmlTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(final long complete, final long target) {
                // todo Do something to update progress...
                LogUtils.d("txoss-->onProgress");
                uiAction(new Runnable() {
                    @Override
                    public void run() {
                        showLoadingDialog(getString(R.string.string_oss_uploading) + BaseMethod.readableStorageSize(complete) + "/" + BaseMethod.readableStorageSize(target));
                    }
                });
            }
        });
        //设置返回结果回调
        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult =
                        (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                hideLoadingDialog();
                String avatarUrl = result.accessUrl;
                LogUtils.d("txoss-->" + avatarUrl);
                uiAction(new Runnable() {
                    @Override
                    public void run() {
                        List<FeedbackUpLoadImageBean> data;
                        if (type == 0) {
                            data = adapterChampion.getData();
                            if (data != null) {
                                FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                                bean.setItemType(0);
                                bean.setUrl(avatarUrl);
                                data.add(data.size() - 1, bean);
                                adapterChampion.setNewInstance(data);
                                adapterChampion.notifyDataSetChanged();
                            }
                        } else if (type == 1) {
                            data = adapterYajun.getData();
                            if (data != null) {
                                FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                                bean.setItemType(0);
                                bean.setUrl(avatarUrl);
                                data.add(data.size() - 1, bean);
                                adapterYajun.setNewInstance(data);
                                adapterYajun.notifyDataSetChanged();
                            }
                        } else if (type == 2) {
                            data = adapterTopFour.getData();
                            if (data != null) {
                                FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                                bean.setItemType(0);
                                bean.setUrl(avatarUrl);
                                data.add(data.size() - 1, bean);
                                adapterTopFour.setNewInstance(data);
                                adapterTopFour.notifyDataSetChanged();
                            }
                        } else if (type == 3) {
                            data = adapterThreePic.getData();
                            if (data != null) {
                                FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                                bean.setItemType(0);
                                bean.setUrl(avatarUrl);
                                data.add(data.size() - 1, bean);
                                adapterThreePic.setNewInstance(data);
                                adapterThreePic.notifyDataSetChanged();
                            }
                        } else if (type == 4) {
                            data = adapterTopFourB.getData();
                            if (data != null) {
                                FeedbackUpLoadImageBean bean = new FeedbackUpLoadImageBean();
                                bean.setItemType(0);
                                bean.setUrl(avatarUrl);
                                data.add(data.size() - 1, bean);
                                adapterTopFourB.setNewInstance(data);
                                adapterTopFourB.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }

            @Override
            public void onFail(CosXmlRequest request,
                               CosXmlClientException clientException,
                               CosXmlServiceException serviceException) {
                hideLoadingDialog();
                if (cosxmlTask.getTaskState() != TransferState.PAUSED) {
                    cosxmlTask = null;
                }
                if (clientException != null) {
                    clientException.printStackTrace();
                } else {
                    serviceException.printStackTrace();
                }
            }
        });
        //设置任务状态回调, 可以查看任务过程
        cosxmlTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(TransferState state) {
                // todo notify transfer state
            }
        });


    }

    //申请结束比赛状态 ：0没有操作权限 1,还没申请 (结束比赛) 2，已经申请，正在审核（审核中） 3，审核通过 （已结束比赛） 4，审核不通过（重新提交）
    private void showBtnStatus(int applayStatus) {
        if (applayStatus == 0) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_no_permission_saiguo_warning);
            mBtnGetCode.setVisibility(View.GONE);
        } else if (applayStatus == 1) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_login_getcode_bg);
            mBtnGetCode.setText(R.string.string_over_game);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 2) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_reviewing);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 3) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_manager_game_btn_gary_bg);
            mBtnGetCode.setText(R.string.string_sure_saiguo_pass_warn);
            mBtnGetCode.setVisibility(View.VISIBLE);
        } else if (applayStatus == 4) {
            mBtnGetCode.setBackgroundResource(R.drawable.drawable_login_getcode_bg);
            mBtnGetCode.setText(R.string.string_resubmit_warn);
            mBtnGetCode.setVisibility(View.VISIBLE);
        }

    }

    //跳过ui
    private void jumpUi(boolean jump) {
        mTvXingThreePic.setVisibility(jump ? View.GONE : View.VISIBLE);
        mTvXingChampionPic.setVisibility(jump ? View.GONE : View.VISIBLE);
        mLlJump.setVisibility(!jump ? View.GONE : View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cosXmlService != null) {
            cosXmlService.release();
        }
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事店级积分赛提交资料界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事店级积分赛提交资料界面");
    }
}
